package com.ucap.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.ucap.util.*;
import com.ucap.weixin.AuthApi;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.WxWsbsSbxx;
import com.ucap.wsbs.model.WxWsbsUserInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Javen 2015年12月5日下午2:20:44
 */
public class WeiXinOauthController extends ApiController {
    static Log log = Log.getLog(WeiXinOauthController.class);

    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
     * ApiConfig 属性值
     */
    public ApiConfig getApiConfig() {
        ApiConfig ac = ApiConfigKit.getApiConfig();

        // 配置微信 API 相关常量
	/*	ac.setToken("caswzx12044");
		ac.setAppId("wx9d1d8ff722708cfd");
		ac.setAppSecret("c5747a020d8c3c453bedce9593fa2b1f");*/
        /**
         * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
         * 2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
        return ac;
    }

    public void oauth2() throws Exception {
        // 测试库(19.111.32.170:9300)回调 （正式库：shenbao.dg.gov.cn）
        String state = getPara("state");
        String redirect_uri = "https://shenbao.dg.gov.cn/dgdcwx/wfw/oauth/index";
        System.out.println("-----" + redirect_uri);
        String oauthurl = SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getApiConfig().getAppId(), redirect_uri, state,
                false);
        setAttr("oauthurl", oauthurl);
        render("/wfw/oauth2.html");
    }

    public void index() {
        try {
            int subscribe = 0;
            // 用户同意授权，获取code
            String code = getPara("code");
            String state = getPara("state");
            String type = getPara("type");
            if (code != null) {
                String appId = ApiConfigKit.getApiConfig().getAppId();
                String secret = ApiConfigKit.getApiConfig().getAppSecret();
                // 通过code换取网页授权access_token
                SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
                // String json=snsAccessToken.getJson();
                String token = snsAccessToken.getAccessToken();
                String openId = snsAccessToken.getOpenid();
                // 拉取用户信息(需scope为 snsapi_userinfo)
                ApiResult apiResult = SnsApi.getUserInfo(token, openId);

                log.warn("getUserInfo:" + apiResult.getJson());
                if (apiResult.isSucceed()) {
                    JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
                    String nickName = jsonObject.getString("nickname");
                    // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                    int sex = jsonObject.getIntValue("sex");
                    String city = jsonObject.getString("city");// 城市
                    String province = jsonObject.getString("province");// 省份
                    String country = jsonObject.getString("country");// 国家
                    String headimgurl = jsonObject.getString("headimgurl");
                    String unionid = jsonObject.getString("unionid");
                    // 获取用户信息判断是否关注
                    ApiResult userInfo = UserApi.getUserInfo(openId);
                    log.warn(JsonKit.toJson("is subsribe>>" + userInfo));
                    if (userInfo.isSucceed()) {
                        String userStr = userInfo.toString();
                        subscribe = JSON.parseObject(userStr).getIntValue("subscribe");
                    }

                    WxWsbsUser.me.save(openId, WeiXinUtils.filterWeixinEmoji(nickName), unionid, headimgurl, country, city,
                            province, sex);
                }
                setSessionAttr("wxUser", WxWsbsUser.me.findByOpenId(openId));
				/*if (subscribe == 0) {
					redirect(PropKit.get("subscribe_rul"));
				} else {*/
                // 根据state 跳转到不同的页面
                //}
                WxWsbsUserInfo userInfo = WxWsbsUserInfo.me.findByOpenId(openId);
                if (userInfo != null) {
                    if ("2".equals(state)) {
                        redirect("/toNavigation?step=11");
                    } else {
                        redirect("/toIndex?step=qyxx");
                    }


                } else {
                    redirect("/wfw/oauth/toAuth");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toAuth() {
        // 测试库(19.111.32.170:9300)回调 （正式库：shenbao.dg.gov.cn）

        try {
            String toUrl = getPara("toUrl");
            if (!StringUtils.isEmpty(toUrl)) {
                setSessionAttr("toUrl", toUrl);
            }
            WxWsbsUser wxUser = (WxWsbsUser) getSessionAttr("wxUser");
            Map<String, String> params = new HashMap<String, String>();
            if (wxUser == null) {
                redirect("/wfw/oauth/oauth2");
            } else {
                params.put("uid", wxUser.get("openid").toString());
                String redirect_uri = "https://iauth.wecity.qq.com/new/cgi-bin/auth.php";
                System.out.println("-----" + redirect_uri);
                String appid = "4744";
                String secretKey = "ba04500d2b145eabfae3145785932c88";
                String plainText = "a=" + appid + "&m=auth&t=" + Util.getCurrentTime() + "&e=" + 600;
                params.put("signature", Signature.getSignature(secretKey, plainText));
                params.put("appid", appid);
                String sblsh = getPara("sblsh");
                if (!StringUtils.isEmpty(sblsh)) {
                    params.put("out_trade_no", sblsh);
                } else {
                    params.put("out_trade_no", "0");
                }
                params.put("redirect", "http://shenbao.dg.gov.cn/dgdcwx/wfw/oauth/auth");


                params.put("type", "0");
                params.put("authurl", redirect_uri);
                //params.put("sceneID","sndc");

                System.out.println(params.toString());

                setAttr("params", params);
                render("/wfw/auth.html");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void auth() {
        JSONObject obj = new JSONObject();
        JSONObject data = null;
        String token = getPara("token");
        String uid = getPara("uid");
        String sblsh = getPara("out_trade_no");
        System.out.println("sblsh:=" + sblsh);
        String appid = "4744";
        String secretKey = "ba04500d2b145eabfae3145785932c88";
        byte[] keyBytes = "b6ad0e874d8a3b4a618139aba24c06db".getBytes();
        try {
            String plainText = "a=" + appid + "&m=getdetectinfo&t=" + Util.getCurrentTime() + "&e=" + 600;

            obj.put("token", token);
            obj.put("appid", appid);
            System.out.println("json--" + obj.toString());
            try {
                String signature = Signature.getSignature(secretKey, plainText);

                System.out.println("请求参数signature: " + signature);
                System.out.println("请求地址url: https://iauth.wecity.qq.com/new/cgi-bin/getdetectinfo.php");
                String resp = HttpRequest.sendPost("https://iauth.wecity.qq.com/new/cgi-bin/getdetectinfo.php",
                        obj.toString(),
                        signature,
                        "application/json"
                );


                obj = JSONObject.parseObject(resp);
                String resultData = obj.getString("data");
                byte[] r = AES.decrypt(resultData.getBytes(), keyBytes);        //AES解密
                data = JSONObject.parseObject(new String(r, "UTF-8"));

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (data != null) {
                String idcard = data.getString("ID");//4501111994xxxxxxxx",
                String name = data.getString("name");//": "张三",
                String phone = data.getString("phone");//": "159********",
                String sex = data.getString("sex");//": "男",
                String nation = data.getString("nation");//": "汉",
                String id_address = data.getString("ID_address");//": "广东省深圳市南山区*****",
                String id_birth = data.getString("ID_birth");//": "xxxx",
                String id_authority = data.getString("ID_authority");//": "***公安局",
                String id_valid_date = data.getString("ID_valid_date");//": "xxxx.xx.xx-xxxx.xx.xx",
                String validatedata = data.getString("validatedata");//": 3344,//数字模式活体检测录制视频读取，动作模式此参数为空
                String frontpic = data.getString("frontpic");//": "身份证正面照片的base64编码",
                String backpic = data.getString("backpic");//": "身份证反面照片的base64编码",
                String video = data.getString("video");//": "视频的base64编码",
                String videopic1 = data.getString("videopic1");//": "视频截图1的base64编码",
                String videopic2 = data.getString("videopic2");//": "视频截图2的base64编码",
                String videopic3 = data.getString("videopic3");//": "视频截图3的base64编码",
                String location = data.getString("location");//":"118.32949|24.566633", //"经度|纬度"(可选)
                String avatar = data.getString("avatar");//":"图片的base64编码",//身份证头像(可选)
                String yt_errorcode = data.getString("yt_errorcode");//":0,//最终结果错误码
                String yt_errormsg = data.getString("yt_errormsg");//":"成功"，//最终结果错误描述
                String livestatus = data.getString("livestatus");//": 0,//活体检测错误码
                String livemsg = data.getString("livemsg");//": "OK",//活体检测错误描述
                String comparestatus = data.getString("comparestatus");//": 0,//活体比对错误码
                String comparemsg = data.getString("comparemsg");//": "OK",//活体比对错误描述
                String type = data.getString("type");//": 0//auth传入的type参数
                WxWsbsUserInfo userInfo = new WxWsbsUserInfo();

                userInfo.set("idcard", idcard);
                userInfo.set("name", name);
                userInfo.set("phone", phone);
                userInfo.set("sex", sex);
                userInfo.set("nation", nation);
                userInfo.set("id_address", id_address);
                userInfo.set("id_birth", id_birth);
                userInfo.set("id_authority", id_authority);
                userInfo.set("id_valid_date", id_valid_date);
                userInfo.set("validatedata", validatedata);
                userInfo.set("frontpic", frontpic);
                userInfo.set("backpic", backpic);
                userInfo.set("video", video);
                userInfo.set("videopic1", videopic1);
                userInfo.set("videopic2", videopic2);
                userInfo.set("videopic3", videopic3);
                userInfo.set("location", location);
                userInfo.set("avatar", avatar);
                userInfo.set("yt_errorcode", yt_errorcode);
                userInfo.set("yt_errormsg", yt_errormsg);
                userInfo.set("livestatus", livestatus);
                userInfo.set("livemsg", livemsg);
                userInfo.set("comparestatus", comparestatus);
                userInfo.set("comparemsg", comparemsg);
                userInfo.set("type", type);
                userInfo.set("openid", uid);
                boolean boo = WxWsbsUserInfo.me.save(uid, userInfo);
                System.out.println("boo=" + boo);
                if (boo) {
                    String toUrl = getSessionAttr("toUrl");
                    if (!StringUtils.isEmpty(toUrl)) {
                        removeSessionAttr("toUrl");
                        redirect(toUrl);
                    } else {
                        if (StringUtils.isEmpty(sblsh) || sblsh.equals("0")) {
                            redirect("/toIndex");
                        } else {
                            WxWsbsSbxx sbxx = WxWsbsSbxx.me.findBySblsh(sblsh);
                            sbxx.set("sfrlsb", "1");
                            sbxx.update();
                            redirect("/toSbpz");
                        }
                    }
                } else {
                    redirect("/wfw/oauth/oauth2");


                }
            }
            //WxWsbsUser.me.save(uid);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * PC扫码登陆回调 获取AccessToken以及用户信息跟微信公众号授权用户用户信息一样
     */
    public void webCallBack() {
        // 用户同意授权，获取code
        String code = getPara("code");
        String state = getPara("state");
        if (code != null) {
            System.out.println("code>" + code + " state>" + state);
            String appId = PropKit.get("webAppId");
            String secret = PropKit.get("webAppSecret");
            // 通过code换取网页授权access_token
            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
            String json = snsAccessToken.getJson();
            System.out.println("通过code获取access_token>>" + json);
            String token = snsAccessToken.getAccessToken();
            String openId = snsAccessToken.getOpenid();
            // 拉取用户信息(需scope为 snsapi_userinfo)
            ApiResult apiResult = SnsApi.getUserInfo(token, openId);

            log.warn("getUserInfo:" + apiResult.getJson());
            if (apiResult.isSucceed()) {
                JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
                String nickName = jsonObject.getString("nickname");
                // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                int sex = jsonObject.getIntValue("sex");
                String city = jsonObject.getString("city");// 城市
                String province = jsonObject.getString("province");// 省份
                String country = jsonObject.getString("country");// 国家
                String headimgurl = jsonObject.getString("headimgurl");
                String unionid = jsonObject.getString("unionid");
            }
            renderText("通过code获取access_token>>" + json + "  \n" + "getUserInfo:" + apiResult.getJson());
        }

    }

}
